package com.shuaitao.newsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuaitao.newsystem.bean.LoginUser;
import com.shuaitao.newsystem.bean.NewsUsers;
import com.shuaitao.newsystem.mapper.NewsUsersMapper;
import com.shuaitao.newsystem.service.NewsUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Objects;

/**
 * @Author 三更  B站： https://space.bilibili.com/663528522
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private NewsUsersService newsUsersService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        NewsUsers newsUsers = newsUsersService.getOne(new QueryWrapper<NewsUsers>().eq("uname", username));
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(newsUsers)){
            throw new RuntimeException("用户名错误");
        }
        LoginUser instance = LoginUser.getInstance();
        instance.setAuthorities(null);
        BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();
        String encode = bCrypt.encode(newsUsers.getUpwd());
        newsUsers.setUpwd(encode);

        //TODO 根据用户查询权限信息 添加到LoginUser中
        ArrayList<String> strings = new ArrayList<>();
//        SysUserRole sysUserRole = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>().eq("user_id", user.getIdNumber()));
//        SysRole id = sysRoleService.getOne(new QueryWrapper<SysRole>().eq("id", sysUserRole.getRoleId()).eq("status",0));
        if (newsUsers.getUname().equals("admin")) {
            strings.add("ROLE_ADMIN");
        }
        //封装成UserDetails对象返回
        instance.setUser(newsUsers);
        instance.setPermissions(strings);
        return instance;
    }
}

